<template>
<q-page padding>
  <p>格式示例文件：<a href="statics/Sample.xlsx">Sample.xlsx</a>
  </p>
  <form class="fileio-form">
    <q-card>
      <q-card-title>
        <p>项目：{{ projectName }}</p>
        <p class="text-faded">ID：{{ projectId }}</p>
        <p>上传样本文件：</p>
        <q-chip
          @click="loadQuota()"
          icon="account_balance_wallet"
          color="primary">样本配额余量{{ quota }}条</q-chip>
      </q-card-title>
      <q-card-main>
        <q-field
          label="模型版本"
          :warning="!locked"
          warning-label="默认为最新版本v2，如果不清楚要做什么，请勿随意改动"
          >
          <q-toggle v-model="locked"
                    checked-icon="locked"
                    unchecked-icon="lock_open"/>
          <q-slider
            :disable="locked"
            :color="locked ? 'primary' : 'warning'"
            label-always
            :min="1" :max="2" :step="1"
            v-model="version"></q-slider>
        </q-field>
        <q-field
          label="输入文件"
          helper="请点击右侧加号图标选择文件，然后点击云图标上传样本文件"
          :error="uploadError"
          :error-label="errorLabel"
          >
          <q-uploader
            color="primary"
            float-label="输入文件"
            extensions=".xls,.xlsx"
            name="input"
            auto-expand
            no-content-type
            :headers="headers"
            :additional-fields="fields"
            @uploaded="uploaded"
            @fail="uploadFail"
            @finish="loadFileIOs"
            :url="fileioUrl"></q-uploader>
        </q-field>
      </q-card-main>
  </q-card>
  </form>
  <a class="download-anchor" href="" download=""></a>
  <q-list multiline>
    <q-list-header>已上传文件列表</q-list-header>
    <q-item-separator />
    <q-item v-for="fileio in fileios"
            :project-id="fileio._id"
            :key="fileio.key"
            >
      <q-item-main>
        <q-card>
          <q-card-title>
            {{ fileio.input.filename }}
            <p class="text-faded">MD5: {{ fileio.input.md5}}</p>
            <div slot="right"><q-icon name="access_time" />{{ datetime(fileio._created) }}</div>
          </q-card-title>
          <q-card-main>
            {{ fileio.output.filename }}
            <p class="text-faded">MD5: {{ fileio.output.md5}}</p>
          </q-card-main>
          <q-card-separator />
          <q-card-actions>
            <q-btn flat @click="download(fileio, 'input')" label="下载输入文件" />
            <q-btn flat @click="download(fileio, 'output')"
                   icon="cloud_download"
                   color="primary" label="下载输出文件" />
          </q-card-actions>
        </q-card>
      </q-item-main>
      <q-item-side right class="column">
        <q-chip icon="create" color="primary">{{ fileio.n_add }}条新增</q-chip>
        <q-chip icon="replay" color="faded">{{ fileio.n_duplicate }}条重复</q-chip>
        <q-chip icon="close" color="negative">{{ fileio.n_fail }}条失败</q-chip>
      </q-item-side>
    </q-item>
  </q-list>
<!-- content -->
</q-page>
</template>

<script>
import {
  mapState
} from 'vuex'

const windownUrl = window.URL || window.webkitURL

export default {
  name: 'FileIO',
  data () {
    return {
      fileios: [],
      version: 2,
      quota: 0,
      locked: true,
      errorLabel: '严重错误：请审查各个字段是否填写有误（如城市未填等）。',
      uploadError: false
    }
  },
  computed: {
    ...mapState('subtoken', [
      'token'
    ]),
    fields () {
      return [
        {
          name: 'clusted_project',
          value: this.projectId
        },
        {
          name: 'v',
          value: this.version
        }
      ]
    },
    headers () {
      return {
        Authorization: this.token
      }
    },
    fileioUrl () {
      return this.$store.state.api.apiRoot + 'clustedFileIO/'
    },
    projectId () {
      return this.$route.params.itemId
    },
    projectName () {
      return this.$route.params.itemName
    }
  },
  created: function () {
    this.loadFileIOs()
    this.loadQuota()
  },
  methods: {
    datetime (gmt) {
      return new Date(gmt).toLocaleString()
    },
    uploadFail (file, xhr) {
      this.uploadError = true
    },
    uploaded (file, xhr) {
      this.uploadError = false
    },
    loadFileIOs () {
      this.$axios.get(
        this.$store.state.api.apiRoot + 'clustedFileIO/?' +
          'where={"clusted_project":"' + this.projectId + '"}' +
          '&sort=-_created',
        { clusted_project: this.projectId })
        .then(
          (response) => {
            const n = response.data._meta.total
            if (n > 0) {
              this.fileios = response.data._items
            }
          })
        .catch(
          (error) => {
            console.log(error)
          })
    },
    loadQuota () {
      this.$axios.get(
        this.$store.state.api.apiRoot + 'quotas/?' +
          'where={"resource":"clusteds"}')
        .then(
          (response) => {
            const n = response.data._meta.total
            if (n > 0) {
              this.quota = response.data._items[0]['quota']
            }
          })
        .catch(
          (error) => {
            console.log(error)
          })
    },
    download (fileio, fileCategory) {
      const fileUrl = fileio[fileCategory].file
      this.$axios.get(
        this.$store.state.api.apiRoot + fileUrl.substring(1),
        { responseType: 'blob' }
      )
        .then(
          (response) => {
            console.log('ok')
            const dataUrl = windownUrl.createObjectURL(response.data)
            const filename = fileio[fileCategory].filename
            const anchor = this.$el.getElementsByClassName('download-anchor')[0]
            anchor.href = dataUrl
            anchor.download = filename
            anchor.click()
          })
        .catch(
          (error) => {
            console.log('error')
            console.log(error)
          })
    }
  },
  watch: {
    token: function (new_, old_) {
      if (new_ === '') {
        this.fileios = []
        return
      }
      this.loadFileIOs()
    }
  }
}

</script>

<style>
</style>
